import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export interface TabbarItem {
  name: string
  value: number | null
  active: boolean
}

// 初始标签栏数据
const initTabbarItems: TabbarItem[] = [
  { name: 'pages/index/index', value: null, active: true },
  { name: 'pages/course/list', value: null, active: false },
  { name: 'pages/profile/index', value: null, active: false },
]

export const useTabbarStore = defineStore(
  'tabbar',
  () => {
    const tabbarItems = ref<TabbarItem[]>([...initTabbarItems])

    // 获取所有标签项
    const getTabbarItems = computed(() => {
      return tabbarItems.value
    })

    // 获取当前激活的标签项
    const getActive = computed(() => {
      const item = tabbarItems.value.find(item => item.active)
      return item || tabbarItems.value[0]
    })

    // 获取指定标签项的值
    const getTabbarItemValue = computed(() => {
      return (name: string) => {
        const item = tabbarItems.value.find(item => item.name === name)
        return item && item.value ? item.value : null
      }
    })

    // 设置标签项的值
    const setTabbarItem = (name: string, value: number): void => {
      const tabbarItem = tabbarItems.value.find(item => item.name === name)
      if (tabbarItem) {
        tabbarItem.value = value
      }
    }

    // 设置标签项的激活状态
    const setTabbarItemActive = (name: string): void => {
      tabbarItems.value.forEach((item) => {
        item.active = item.name === name
      })
    }

    const reLaunch = () => {
      setTabbarItemActive('/pages/index/index')
      uni.reLaunch({
        url: '/pages/index/index',
      })
    }

    const goLogin = () => {
      setTabbarItemActive('pages/profile/index')
      nextTick(() => {
        uni.switchTab({
          url: '/pages/profile/index',
        })
      })
    }

    const logout = () => {
      uni.clearStorage()
      setTabbarItemActive('pages/index/index')
      nextTick(() => {
        uni.switchTab({
          url: '/pages/index/index',
        })
      })
    }

    return {
      tabbarItems,
      reLaunch,
      goLogin,
      logout,
      getTabbarItems,
      getActive,
      getTabbarItemValue,
      setTabbarItem,
      setTabbarItemActive,
    }
  },
  {
    persist: false,
  },
)
